package com.zjl.legendary.controller;

import com.zjl.legendary.entity.User;
import com.zjl.legendary.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author zhoujingluo
 * @date 2021/6/14 11:25
 */
@Controller
@RequestMapping("/api/user")
public class UserController {
    @Autowired
    private UserServiceImpl userService;

    /**
     * 用户登录
     * @param nickname 用户名
     * @param password 密码
     * @param req 请求
     * @return 响应结果
     */
    @RequestMapping("/login.do")
    public String login(String nickname, String password, HttpServletRequest req){
        if (userService.login(nickname,password,req.getSession())) {
            //登录成功
            return "redirect:/index.jsp";
        } else {
            //登录失败
            //给页面传递信息，提示用户昵称或密码错误
            req.setAttribute("msg","fail");
            return "forward:/login.jsp";
        }
    }

    /**
     * 用户注册
     * @param nickname 用户名
     * @param password 密码
     * @param req 请求
     * @return 响应结果
     */
    @RequestMapping("/register.do")
    public String register(String nickname,String password,HttpServletRequest req){
        if (userService.register(nickname,password)) {
            //注册成功
            return "redirect:/login.jsp";
        } else {
            //注册失败
            //给前端页面传递信息，提示用户注册失败
            req.setAttribute("msg","fail");
            return "forward:/register.jsp";
        }
    }

    /**
     * 验证用户名是否可用
     * @param nickname 用户名
     * @return 返回响应结果
     */
    @RequestMapping("/check.do")
    public String check(String nickname){
        return userService.checkName(nickname) ? "success" : "fail";
    }

    /**
     * 展示所有用户
     * @param req 请求
     * @return 响应结果
     */
    @RequestMapping("/show.do")
    public String show(HttpServletRequest req){
        List<User> ulist = userService.showAll();
        req.setAttribute("ulist",ulist);
        return "forward:/userlist.jsp";
    }

    /**
     * 退出登录
     * @param session session域
     * @return 响应结果
     */
    @RequestMapping("/logout.do")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        return "redirect:/login.jsp";
    }
}
